package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationServiceImpl categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("brand_id", key)
                    .or()
                    .like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void updateDetail(BrandEntity brand) {
        // 更新品牌
        this.updateById(brand);
        // 保证冗余字段的数据一致
        if (StringUtils.isNotEmpty(brand.getName())) {
            categoryBrandRelationService.updateBrandNameByBrandId(brand.getBrandId(), brand.getName());
            // TODO 更新其他关联
        }

    }

    @Override
    public List<BrandEntity> listBransByCatId(Long catId) {
        // 查询出该分类 分类与品牌关联
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities = categoryBrandRelationService.list(Wrappers
                .<CategoryBrandRelationEntity>lambdaQuery()
                .eq(CategoryBrandRelationEntity::getCatelogId, catId));
        // 获取品牌id集合
        List<Long> brandIds = categoryBrandRelationEntities
                .stream()
                .map(CategoryBrandRelationEntity::getBrandId)
                .collect(Collectors.toList());
        // 查询品牌
        if (CollectionUtils.isEmpty(brandIds)) {
            return Collections.emptyList();
        }
        Collection<BrandEntity> brandEntities = this.listByIds(brandIds);
        return (List<BrandEntity>) brandEntities;
    }

}
